package com.mentalhealthplatform.studentV3.service;

import com.mentalhealthplatform.appModels.Test;
import com.mentalhealthplatform.studentV3.repository.TestRepositoryV3;
import jakarta.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Pear
 */
@Service
public class TestServiceV3 {

    @Autowired
    private TestRepositoryV3 testRepository;

    public List<Test> findAll() {
        return testRepository.findAll();
    }

    public Test findById(Integer id) {
        return testRepository.findById(id).orElse(null);
    }

    public Test save(Test test) {
        return testRepository.save(test);
    }

    public void deleteById(Integer id) {
        testRepository.deleteById(id);
    }

    @Transactional
    public List<Test> getRandomTestsAndSetStatus(int count, Integer type) {
        List<Test> tests = testRepository.findRandomTests(count, type);
        if (tests.isEmpty()) {
            System.out.println("获取到的题目列表为空");
            return new ArrayList<>();
        }

        // 将获取到的题目的状态改为 1
        List<Integer> questionIds = tests.stream().map(Test::getId).toList();
        testRepository.updateStatusInBatch(questionIds, 1);

        return tests;
    }


    @Transactional
    public void updateTestStatus(List<Integer> questionIds, Integer status) {
        if (questionIds == null || questionIds.isEmpty()) {
            // 如果ID列表为空，可以选择跳过更新操作或者记录日志
            System.out.println("ID列表为空，跳过更新操作");
            return;
        }
        testRepository.updateStatusInBatch(questionIds, status);
    }

}
